package com.huage.courseplatform.framework.handler;

import com.huage.courseplatform.framework.enums.ResultCode;
import com.huage.courseplatform.framework.utils.ResultUtils;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;


/**
 * 异常捕获，统一格式返回
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理统一异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultUtils exceptionHandler(Exception e) {
        log.error("Exception:", e);
        return ResultUtils.error();
    }

    /**
     * 校验异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultUtils methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        //log.error("MethodArgumentNotValidException:", e);
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResultUtils.error(ResultCode.BAD_REQUEST.getCode(),msg);
    }




    /**
     * 捕获断言校验异常
     */
    @ExceptionHandler({IllegalArgumentException.class})
    public ResultUtils illegalArgumentException(Exception e) {
        //log.error("触发异常拦截: " + e.getMessage(), e);
        return ResultUtils.error(ResultCode.BAD_REQUEST.getCode(),e.getMessage());
    }

    /**
     * 捕获断言校验异常
     */
    @ExceptionHandler({IOException.class})
    public ResultUtils ioException(Exception e) {
        log.error("io异常拦截: " + e.getMessage(), e);
        return ResultUtils.error(ResultCode.BAD_REQUEST.getCode(),"文件流错误："+e.getMessage());
    }







}
